<template>
  <div class="conter">
    <el-empty v-if="!login_status" description="请先登录快手">
      <el-button type="primary" @click="logingKuais">立即登录</el-button>
    </el-empty>
    <div class="crynter" v-else>
      <el-form :inline="true" :model="variables" class="demo-form-inline">
        <el-form-item label="用户名">
          <el-input v-model="variables.keyword" placeholder="输入用户名"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onFindUserFun">搜索</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="ongetNas">选择保存位置</el-button>
        </el-form-item>
        <el-form-item label="保存到">
          <el-tag>{{path}}</el-tag>
        </el-form-item>
        <el-form-item label="下载前几条">
          <el-input v-model="dow_now_num" placeholder="下载前面数量"></el-input>
        </el-form-item>
      </el-form>
      <el-form :inline="true" :model="variables" class="demo-form-inline">
        <el-form-item label="搜索内容">
          <el-input v-model="variables.keyword" placeholder="输入内容"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onFindUserFunwe">搜索</el-button>
        </el-form-item>
        <!-- <el-form-item>
          <el-button type="primary" @click="ongetNas">选择保存位置</el-button>
        </el-form-item> -->
        <!-- <el-form-item label="保存到">
          <el-tag>{{path}}</el-tag>
        </el-form-item> -->
        <!-- <el-form-item label="下载前几条">
          <el-input v-model="dow_now_num" placeholder="下载前面数量"></el-input>
        </el-form-item> -->
      </el-form>
      <el-row v-if="userlister" class="sunehbbouer">
        <el-col :span="8" class="sunehb" v-if="sheardater === 1">
          <div class="userlist">
            <div class="lister" :class="{selectconetr: item.status}" v-for="item in selectconter" :key="item.user_id" @click="selecttietm(item)">
              <!-- <div class="nolietr" v-if="item.type && item.type==='no_more'">
                {{item.title}}
              </div> -->
              <div class="lerudr">
                <img :src="item.headurl" class="userimgse" alt="">
              </div>
              <div class="rightsocnghe">
                <div class="topusername">{{item.user_name}}</div>
                <div class="juers" v-if="item.user_text">{{item.user_text}}</div>
              </div>
            </div>
          </div>
          <el-button type="primary" @click="dow_all">{{sheardater === 1?'批量下载': '批量复制'}}</el-button>
          <el-tag>已选择{{selectconter.length}}个</el-tag>
        </el-col>
        <el-col :span="8" class="sunehb" v-if="sheardater === 2">
          <div class="userlist" id="copycode">
            <div class="lister" :class="{selectconetr: item.status}" v-for="item in selectconter" :key="item.user_id" @click="selecttietm(item)">

              <div class="rightsocnghe">
                <div class="topusername">{{item.photo.photoUrl}}</div>
              </div>
            </div>
          </div>
          <el-button type="primary" @click="dow_all">{{sheardater === 1?'批量下载': '批量复制'}}</el-button>
          <el-tag>已选择{{selectconter.length}}个</el-tag>
        </el-col>
        <el-col :span="16" class="sunehb" v-if="sheardater === 1">
          <div class="userlist" v-infinite-scroll="onsercherFunsuioyenr" :infinite-scroll-delay="1000" :infinite-scroll-distance="5">
            <div class="lister" :class="{selectconetr: item.status}" v-for="item in userlister" :key="item.user_id" @click="selecttietm(item)">
              <div class="lerudr">
                <img :src="item.headurl" class="userimgse" alt="">
              </div>
              <div class="rightsocnghe">
                <div class="topusername">{{item.user_name}}</div>
                <div class="juers" v-if="item.user_text">{{item.user_text}}</div>
              </div>
            </div>
          </div>
          <el-button type="primary" @click="selectAll">{{selecttitle.title}}</el-button>
          <el-tag>已加载{{userlister.length}}条</el-tag>
        </el-col>
        <el-col :span="16" class="sunehb usher" v-if="sheardater === 2">
          <div class="userlist" v-infinite-scroll="onsercherFunsuioyenr" :infinite-scroll-delay="1000" :infinite-scroll-distance="5">
            <div class="lister" :class="{selectconetr: item.status}" v-for="item in userlister" :key="item.user_id" @click="selecttietm(item)">
              <div class="lerudr">
                <img :src="item.photo.animatedCoverUrl" class="derr" alt="">
              </div>
              <!-- <div class="rightsocnghe">
                <div class="topusername">{{item.user_name}}</div>
                <div class="juers" v-if="item.user_text">{{item.user_text}}</div>
              </div> -->
            </div>
          </div>
          <el-button type="primary" @click="selectAll">{{selecttitle.title}}</el-button>
          <el-tag>已加载{{userlister.length}}条</el-tag>
        </el-col>
      </el-row>
    </div>
    <div class="errifrpm" v-if="code_url">
      <iframe id="projectIframe" :src="code_url" frameborder="0" class="ifroms"></iframe>
      <!-- <el-button @click="juhergt">提交</el-button> -->
    </div>
    <el-dialog title="提示" :visible.sync="selectnas" width="30%" :modal-append-to-body="false" :before-close="selectnasClose">
      <div class="lisetrbox">
        <div class="sletyure" v-for="item in nas_dir_list" :key="item.name" @click="gotocomyer(item)">{{item.name}}</div>
      </div>
      <span slot="footer" class="dialog-footer">
        <!-- <el-button @click="selectnas = false">取 消</el-button> -->
        <el-button type="primary" @click="gotohonme">回首页</el-button>
        <el-button type="primary" @click="selectnas = false">确 定</el-button>
      </span>
    </el-dialog>
    <el-drawer title="创建进度" :modal="false" size="100%" :show-close="false" :close-on-press-escape="false" :visible.sync="cretedeStatusDarwer" direction="ttb" :before-close="clearDarwer">
      <div class="interbox">
        <h1 class="ontinters">{{titles}}</h1>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { check_token, kuaishou_find } from "../../api/kuaishoudow_video";
import { get_nas, dow_kuaishou_video } from "../../api/my_server";
import config from '../../api/config'

export default {

  data () {
    return {
      login_status: false,
      variables: {
        keyword: '',
        pcursor: '',
        searchSessionId: ''
      },
      p_variables: {
        page: 'profile',
        pcursor: '',
        userId: ''
      },
      userlister: null,
      dow_user_list: null,
      up_dow_foderliset: [],
      const_dow_user_info: {},
      code_url: '',
      selectnas: false,
      path: '/',
      nas_dir_list: null,
      cretedeStatusDarwer: false,
      titles: '*正在处理，请勿退出或刷新页面',
      dow_now_num: '',
      sheardater: 1
    }
  },
  computed: {
    selecttitle () {
      let selectAlls = true
      this.userlister.forEach(res => {
        if (!res.status) {
          selectAlls = false
        }
      })
      if (selectAlls) {
        return {
          selectAlls,
          title: '取消全选'
        }
      } else {
        return {
          selectAlls,
          title: '全选'
        }
      }
    },
    selectconter () {
      return this.userlister.filter(res => {
        return res.status
      })
    }
  },
  created () {
    this.check_token_fun()
  },
  methods: {
    //方法一：用原生的document.execCommand(‘copy’)的方式实现，移动端和PC端都可以使用
    //效果：点击复制按钮，复制想复制的区域，例如复制邀请码功能实现
    handleCopy () {
      const range = document.createRange(); //创建range对象
      range.selectNode(document.getElementById('copycode')); //获取复制内容的 id 选择器
      const selection = window.getSelection();  //创建 selection对象
      if (selection.rangeCount > 0) selection.removeAllRanges(); //如果页面已经有选取了的话，会自动删除这个选区，没有选区的话，会把这个选取加入选区
      selection.addRange(range); //将range对象添加到selection选区当中，会高亮文本块
      document.execCommand('copy'); //复制选中的文字到剪贴板
      this.$message.success(`内容已复制`)
      selection.removeRange(range); // 移除选中的元素
    },
    clearDarwer () {
      console.log('上传进度')
    },
    gotocomyer (item) {
      this.path = this.path + item.name + '/'
      this.ongetNas()
    },
    selectnasClose () {
      this.selectnas = false
    },
    gotohonme () {
      this.path = '/'
      this.ongetNas()
    },
    ongetNas () {
      get_nas.bind(this)({ path: this.path }).then(res => {
        console.log('res', res)
        try {
          const jsonData = JSON.parse(res)
          this.nas_dir_list = jsonData.data.filter(wer => {
            return wer.type === 'd'
          })
          this.selectnas = true
        } catch (error) {

        }
      })
    },
    leitenifroms () {
      window.addEventListener('message', this.receiveMessage, false);
    },
    receiveMessage (event) {
      try {
        const jsonData = JSON.parse(event.data)
        console.log('jsonData', jsonData)
        if (jsonData.msgType === 'RESULT') {
          console.log('timese', jsonData.msg)
          this.code_url = ''
          const herides = {
            'identity-verification-type': 2,
            "identity-verification-token": jsonData.msg.token
          }
          this.dow_api_gets(this.const_dow_user_info, herides)
        }
      } catch (error) {

      }
    },
    copydata () {
      this.handleCopy()
      console.log('this.up_dow_foderliset', this.selectconter)

      let conter = this.selectconter.map(res => {
        return res.photo.photoUrl
      })
      console.log('conter', conter)
    },
    // 点击下载
    dow_all () {
      if (this.sheardater === 2) {
        this.copydata()
        return
      }
      if (!this.selectconter || !this.selectconter.length) {
        this.$message.error('请选择用户')
        return
      }
      this.dow_user_list = this.selectconter.map(res => {
        return { user_id: res.user_id, name: res.user_name }
      })
      if (this.path === '/') {
        this.$message.error('请选择保存文件位置')
        return
      }
      this.cretedeStatusDarwer = true
      this.dow_finders()
    },
    // 过滤下载选中用户
    dow_finders () {
      if (!this.dow_user_list || !this.dow_user_list.length) {
        this.titles = '已处理完成，等待服务器处理完成'
        this.$message.success('已处理完成所有用户')
        return
      }
      const user = this.dow_user_list.splice(0, 1)[0]
      this.const_dow_user_info = user
      this.up_dow_foderliset = []
      this.p_variables.pcursor = ''
      this.dow_api_gets(user)
    },
    // 获取下载的用户视频
    dow_api_gets (user, herides = {}) {
      this.p_variables.userId = user.user_id

      const querydata = {
        variables: {
          ...this.p_variables
        },
        ...config.kuaishou_video.query_data.find_photos
      }
      kuaishou_find.bind(this)(querydata, herides).then(res => {
        try {
          const jsonData = JSON.parse(res)
          if (jsonData.errors && jsonData.errors.length) {
            this.code_url = jsonData.data.captcha.url
            this.leitenifroms()
            return
          }

          if (jsonData.data && jsonData.data.visionProfilePhotoList && jsonData.data.visionProfilePhotoList.result === 1) {

            if (jsonData.data.visionProfilePhotoList.pcursor !== 'no_more') {
              this.up_dow_foderliset.push(...jsonData.data.visionProfilePhotoList.feeds)
              this.p_variables.pcursor = jsonData.data.visionProfilePhotoList.pcursor
              // const dows = Math.ceil(Math.random() * 10) * 200
              // console.log('dows', dows)
              if (this.dow_now_num) {
                if (this.up_dow_foderliset.length >= (this.dow_now_num * 1)) {
                  this.$message.success(`${user.name}的视频已处理完成等待下载`)
                  this.up_server_dow()
                  return
                }
                setTimeout(_ => {
                  this.dow_api_gets(user)
                }, 3500)
              } else {
                setTimeout(_ => {
                  this.dow_api_gets(user)
                }, 3500)
              }

              // setTimeout(_ => {
              // }, dows)
              return
            }
            this.$message.success(`${user.name}的视频已处理完成等待下载`)
            this.up_server_dow()
          }
        } catch (error) {
          console.log('err', error)
          this.dow_api_gets(user)
        }
      })
    },
    // 上传到服务端进行下载
    up_server_dow () {
      console.log('this.up_dow_foderliset', this.up_dow_foderliset, this.const_dow_user_info)
      const up_filserdow_data = {
        data: this.up_dow_foderliset,
        path: this.path,
        ...this.const_dow_user_info,
        user_id_ks: localStorage.getItem('userId')
      }
      console.log('up_filserdow_data', up_filserdow_data)
      dow_kuaishou_video.bind(this)(up_filserdow_data).then(res => {
        this.dow_finders()
        console.log('res', res)
      })
      // setTimeout(_ => {
      // }, 1000)
    },
    selectAll () {
      const selectAlls = !this.selecttitle.selectAlls
      this.userlister.forEach(res => {
        res.status = selectAlls
      })
    },
    selecttietm (item) {
      item.status = !item.status
    },
    check_token_fun () {
      const fondata = 'sid=kuaishou.server.web'
      check_token.bind(this)(fondata).then(res => {
        try {
          const jsonData = JSON.parse(res)
          this.login_status = jsonData.result !== 100110000
        } catch (error) {

        }
      })
    },
    logingKuais () {
      document.getElementsByClassName('user-default')[0].click()
      const cleurt = document.getElementsByClassName('tm-button')
      cleurt[cleurt.length - 1].click()
    },
    onsercherFunsuse () {
      if (this.variables.pcursor && this.variables.pcursor === 'no_more') {
        this.$message.error('没有更多数据了...')
        // this.userlister.push({
        //   type: 'no_more',
        //   title: '没有更多数据了...'
        // })
        return
      }
      const data = {
        variables: {
          ...this.variables
        },
        ...config.kuaishou_video.query_data.find_center
      }
      kuaishou_find.bind(this)(data).then(res => {
        console.log('.res', res)
        try {
          const jsonData = JSON.parse(res)
          if (jsonData.data && jsonData.data.visionSearchPhoto && jsonData.data.visionSearchPhoto.result === 1) {
            this.variables.pcursor = jsonData.data.visionSearchPhoto.pcursor
            this.variables.searchSessionId = jsonData.data.visionSearchPhoto.searchSessionId
            const datsheuy = jsonData.data.visionSearchPhoto.feeds.map(rew => {
              rew.status = false
              return rew
            })
            console.log('this.userlister', this.userlister)
            if (this.variables.pcursor * 1 === 1) {
              this.userlister = datsheuy
            } else {
              this.userlister.push(...datsheuy)
            }
            return
          }
          this.$message.error('搜索失败-1')
          // this.$message.success('批量创建已完成，将在3秒后刷新页面')
        } catch (error) {
          this.$message.error('搜索失败-2')
        }
      })
    },
    onsercherFuns () {
      if (this.variables.pcursor && this.variables.pcursor === 'no_more') {
        this.$message.error('没有更多数据了...')
        // this.userlister.push({
        //   type: 'no_more',
        //   title: '没有更多数据了...'
        // })
        return
      }
      const data = {
        variables: {
          ...this.variables
        },
        ...config.kuaishou_video.query_data.find_user
      }
      kuaishou_find.bind(this)(data).then(res => {
        try {
          const jsonData = JSON.parse(res)
          if (jsonData.data && jsonData.data.visionSearchUser && jsonData.data.visionSearchUser.result === 1) {
            this.variables.pcursor = jsonData.data.visionSearchUser.pcursor
            this.variables.searchSessionId = jsonData.data.visionSearchUser.searchSessionId
            const datsheuy = jsonData.data.visionSearchUser.users.map(rew => {
              rew.status = false
              return rew
            })
            console.log('this.userlister', this.userlister)
            if (this.variables.pcursor * 1 === 1) {
              this.userlister = datsheuy
            } else {
              this.userlister.push(...datsheuy)
            }
            return
          }
          this.$message.error('搜索失败-1')
          // this.$message.success('批量创建已完成，将在3秒后刷新页面')
        } catch (error) {
          this.$message.error('搜索失败-2')
        }
      })
    },
    onsercherFunsuioyenr () {
      if (this.sheardater === 1) {
        this.onsercherFuns()
        return
      }
      this.onsercherFunsuse()
    },
    onFindUserFun () {
      delete this.variables.pcursor
      delete this.variables.searchSessionId
      this.sheardater = 1
      this.onsercherFuns()
    },
    onFindUserFunwe () {
      delete this.variables.pcursor
      delete this.variables.searchSessionId
      this.sheardater = 2
      this.onsercherFunsuse()
    },
    addInfosder () {
      console.log('addInfosder')
    }
  },
}
</script>